package com.surfilter.gsxt.util;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.List;

/**
 * Created by jstarseven on 2017/3/2.
 */
public class FileWriteUtils {

    private static final Logger logger = LoggerFactory.getLogger(FileWriteUtils.class);

    /**
     * 写入单一对象
     * @param obj
     * @param file_path
     * @param file_name
     * @throws Exception
     */
    public static void writeToFileByLine(Object obj, String file_path, String file_name) throws Exception {
        writeToFileByLineIgnore(Lists.newArrayList(obj), file_path, file_name, null);
    }

    /**
     * 批量写入数据
     * @param list
     * @param file_path
     * @param file_name
     * @throws Exception
     */
    public static void writeToFileByLine(List list, String file_path, String file_name) throws Exception {
        writeToFileByLineIgnore(list, file_path, file_name, null);
    }

    /**
     * 批量写入请忽略对象某些字段
     * @param list
     * @param file_path
     * @param file_name
     * @param gson
     * @throws Exception
     */
    public static void writeToFileByLineIgnore(List list, String file_path, String file_name, Gson gson) throws Exception {
        if (list != null && list.size() > 0) {
            File dir = new File(file_path);
            if (!dir.exists())
                org.apache.commons.io.FileUtils.forceMkdir(dir);
            String fp = file_path + "/" + file_name;
            try (PrintWriter writer = new PrintWriter(new FileWriter(fp, true))) {
                StringBuilder builder = new StringBuilder();
                if (list.size() == 1) {
                    builder.append(gson == null ? JSONObject.toJSONString(list.get(0)) : gson.toJson(list.get(0)));
                } else {
                    for (Object obj : list) {
                        builder.append("\n");
                        builder.append(gson == null ? JSONObject.toJSONString(obj) : gson.toJson(obj));
                    }
                }
                writer.println(builder.toString().replaceFirst("\n", ""));
            }
        }
    }


    /**
     * 批量写入请忽略对象某些字段
     * @param list
     * @param file_path
     * @param file_name
     * @throws Exception
     */
    public static void writeListToFileByLine(List list, String file_path, String file_name) throws Exception {
        Gson gson = new Gson();
        if (list != null && list.size() > 0) {
            File dir = new File(file_path);
            if (!dir.exists())
                org.apache.commons.io.FileUtils.forceMkdir(dir);
            String fp = file_path + "/" + file_name;
            try (PrintWriter writer = new PrintWriter(new FileWriter(fp, true))) {
                writer.println(gson.toJson(list));
            }
        }
    }

}
